<template>
  <div class="timer">
    {{ showText }}<template v-if="showMillisecond && counter > 0">{{ millisecond }}</template>
  </div>
</template>

<script>
/**
 * Demo:
 *
 * <timer
 * :time="'2021-09-12 17:17:32'"
 * :duration="3600 x 24"
 * :show-millisecond="true"
 * @over="handleOver" />
 */
export default {
  name: 'Timer',
  /*
    begin time
    duration / s
   */
  props: {
    time: {
      type: String,
      default: '2021-09-12 17:50:35'
    },
    duration: {
      type: Number,
      default: 3600 * 24
    },
    showMillisecond: {
      type: Boolean,
      default: true
    },
    overText: {
      type: String,
      default: '已经结束了'
    }
  },
  data() {
    return {
      counter: 0,
      millisecond: '',
      showText: '',
      millisecondTimerRun: false
    }
  },
  methods: {
    format() {
      return new Promise(resolve => {
        if (this.counter <= 0) {
          this.$emit('over')
          resolve(this.overText)
        }
        const hour = Number.parseInt(this.counter / 3600)
        const minute = Number.parseInt((this.counter - hour * 3600) / 60)
        const second = this.counter % 60
        // resolve(`${hour}小时,${minute}分,${second}秒`)
        resolve(`${hour}:${minute}:${second}`)
      })
    },
    timer() {
      setTimeout(() => {
        if (this.counter > 0) {
          this.counter--
          this.format().then(response => {
            this.showText = response + (this.showMillisecond ? '.' : '')
            if (!this.millisecondTimerRun) {
              this.millisecondTimerRun = true
              this.millisecondTimer()
            }
          })
          this.timer()
        }
      }, 1000)
    },
    millisecondTimer() {
      if (this.counter > 0) {
        setTimeout(() => {
          if (this.millisecond > 0) {
            let i = this.millisecond - 1
            if (i <= 0) {
              i = 10
            }
            this.millisecond = i
          } else {
            this.millisecond = 10
          }
          this.millisecondTimer()
        }, 100)
      }
    }
  },
  created () {
    const time = new Date(this.time.replace(/-/g, '/')).getTime() / 1000
    const now = Number.parseInt(new Date().getTime() / 1000)
    this.counter = time + this.duration - now
    if (this.counter <= 0) {
      this.$emit('over')
    } else {
      this.timer()
    }
  }
}
</script>

<style scoped lang="stylus">
//.timer
  //background black
  //height 35px
  //line-height 35px
  //color white
</style>
